package com.android.interfata;


import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ParseException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

import com.android.lazylist.LazyAdapter;

public class Bookmark extends Activity implements Runnable
{
    ListView list;
    LazyAdapter adapter;

    private ProgressDialog pd;
	boolean primaData = true;

    public String[] title;
	public String[] detail;	
	public String[] imgid; 	
	public Double[] rating, price;	
	public String[] authors, brand;	
	public Long[] id;	
	public String[] imageLarge;	
	public String[] linkAmazon, linkEbay; 
	
	public int scrHeight, scrWidth;

    int numResults = 0;

	public String[] categories = { "", "", "", "", "Books", "Multimedia", "Music", "", "Movies", 
			"Electronics", "Computers", "Cameras", "Ebooks", "Software"};

	private String pozaDefault = "http://mail.pioneerinvestments.ro:333/images/img.jpg";
	
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bookmark1);
        
        /* username si logout din heade - le completez cu datele corespunzatoare */
        TextView user = (TextView) findViewById(R.id.userHeader);
        SharedPreferences logPref = getSharedPreferences("LoginPref", MODE_PRIVATE);
    	String username = logPref.getString("user", "username");
    	user.setText(username);		
    	
        TextView logout = (TextView) findViewById(R.id.logoutHeader);
		/**** delogare ****/
		logout = (TextView) findViewById(R.id.logoutHeader);
		logout.setOnClickListener(new View.OnClickListener() 
		{
            public void onClick(View v) 
            {
            	askOK();
            }
        });
		/**** end delogare ****/

		Log.d("book", "create");
		//pd = ProgressDialog.show(this, "Working..", "Loading data", true, false);
		
		pd = new ProgressDialog(this);
		pd.setIndeterminate(true);
		pd.setIndeterminateDrawable(getResources().getDrawable(R.anim.loading_anim));
		pd.setMessage("Loading data. Please wait");
		//pd.setTitle("Cotrobaing...");
		pd.setCancelable(false);
		pd.show();
		
		Thread thread = new Thread(this);
		thread.start();
        
    }
    
    @Override
    public void onResume()
    {
    	super.onResume();  //The activity is about to become visible.
		if (primaData == false)
		{
			Log.d("book", "resume" + primaData);
			//pd = ProgressDialog.show(this, "Working..", "Loading data", true, false);
			
			pd = new ProgressDialog(this);
			pd.setIndeterminate(true);
			pd.setIndeterminateDrawable(getResources().getDrawable(R.anim.loading_anim));
			pd.setMessage("Loading data. Please wait");
			//pd.setTitle("Cotrobaing...");
			pd.setCancelable(false);
			pd.show();
	
			Thread thread = new Thread(this);
			thread.start();
		}
		else
		{
			primaData = false;
		}
    }
    
    @Override
    public void onDestroy()
    {
        list.setAdapter(null);
        super.onDestroy();
    }
    
    
    /* thread pentru acces la server */
    public void run() 
    {
            //pi_string = Pi.computePi(800).toString()
    	try 
		{
	    	getDataForList();
		} 
		catch (ParseException e) 
		{
			e.printStackTrace();
		}
        
		handler.sendEmptyMessage(0);
    }

    private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) 
            {
                pd.cancel();
                //tv.setText(pi_string);*/
                try
                {
            		getSize();
                	populare();
                }
		    	catch( Exception e)
		    	{
		    		Log.d("err - handle populare", "err" + e.getLocalizedMessage());
		    	}
            }
    };
    /* end thread pentru acces la server */
    
    
    // populez lista
    public void populare ()
    {
        list=(ListView)findViewById(R.id.list);
        adapter=new LazyAdapter(this, imgid, title, detail, rating, price, imageLarge, 
        		linkAmazon, linkEbay, id, authors, brand, scrHeight, scrWidth);
        list.setAdapter(adapter);
    }

    
	// preiau dimensiunile ecranului
    private void getSize ()
    {
 		Display display = getWindowManager().getDefaultDisplay(); 
		scrWidth = (int)display.getWidth();  
		scrHeight = (int)display.getHeight(); 
    }
    

	/* preluare date din xml */
	public void getDataForList()
    {
    	try
    	{
    		// preiau datele din SharedPref
    		SharedPreferences logPref = getSharedPreferences("LoginPref", MODE_PRIVATE);
	    	String idUser = logPref.getInt("ID", 0) + "";
	    	String user = logPref.getString("user", "username");
	    	String pass = logPref.getString("pass", "pass");
	    	
	    	
	    	// numarul paginii si nr de rasp pe pagina - ! de adaugat ceva gen nextPage daca nu am luat toate rez
	    	int nrPag = 0;
	    	int nrRaspPag = 20;
	    	String xml = XMLfunctions.getXML("GetUserBookmarks?UserID=" + idUser + "&UserUsername=" + user + "&Password=" + pass 
	    				+ "&Pagina=" + nrPag + "&IntrariPePagina=" + nrRaspPag);
	    	//Log.d("xml", xml);
    		
    		
    		
	        Document doc = XMLfunctions.XMLfromString(xml);
	        
	        numResults = XMLfunctions.numResults(doc, "name");
	        if (numResults <= 0)
	        {
	        	initializari(1);
	        	title[0] = "-";
				detail[0] = "-";							
				imgid[0] = pozaDefault;				
				rating[0] = 0.0;
				price[0] = 0.0;				
				id[0] = Long.parseLong("0");
				brand[0] = "-";
				authors[0] = "-";				
				imageLarge[0] = pozaDefault;
				linkAmazon[0] = "-";
				linkEbay[0] = "-";
	        }
	        else
	        {     
	        	initializari(numResults);
	        	
		        NodeList nodes = doc.getElementsByTagName("TipProdus");
		       		        
		        for (int i = 0; i < nodes.getLength(); i++)
				{							
					Element e = (Element)nodes.item(i);
					title[i] = XMLfunctions.getValue(e, "name");
					detail[i] = categories[Integer.parseInt(XMLfunctions.getValue(e, "categ_id"))];
								
					if (XMLfunctions.getValue(e, "imageSmall") == "")
						imgid[i] = pozaDefault;
					else
						imgid[i] = XMLfunctions.getValue(e, "imageSmall");
					
					Log.d("poza", imgid[i]);
					
					rating[i] = Double.parseDouble(XMLfunctions.getValue(e, "Rating"));
					price[i] = Double.parseDouble(XMLfunctions.getValue(e, "Price"));
					
					id[i] =  Long.parseLong(XMLfunctions.getValue(e, "ID"));
					brand[i] =  XMLfunctions.getValue(e, "brand");
					authors[i] =  XMLfunctions.getValue(e, "authors");
					
					imageLarge[i] =  XMLfunctions.getValue(e, "imageLarge");
					
					//Linkuri catre ebay Amazon
					
					linkAmazon[i] =  XMLfunctions.getValue(e, "linkAmazon");
					linkEbay[i] =  XMLfunctions.getValue(e, "linkEbay");
					
				}	
	        }
		   // populareLista();
    	}
    	catch( Exception e)
    	{
    		Log.d("err - getDataForList", e.getLocalizedMessage());
    	}
    }
	
	
	private void initializari(int numResults)
	{
	    title = new String[numResults];
 		detail = new String[numResults];
 		imgid = new String[numResults]; 
		rating = new Double[numResults];
		price = new Double[numResults];
		brand = new String[numResults];
		authors = new String[numResults];
		id =  new Long[numResults];
		imageLarge = new String[numResults];
		linkAmazon = new String[numResults];
		linkEbay = new String[numResults];
	}
	
	


	/**** delogare ****/
	private void askOK()
	{
		DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
		    public void onClick(DialogInterface dialog, int which)
		    {
		        switch (which)
		        {
			        case DialogInterface.BUTTON_POSITIVE:
			        	delPref();
			        	gotoLogin();
			        	break;
	
			        case DialogInterface.BUTTON_NEGATIVE:
			            //No button clicked
			            break;
		        }
		    }
		};

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Are you sure you want to logout?").setPositiveButton("Yes", dialogClickListener)
		    .setNegativeButton("No", dialogClickListener).show();
	}

	private void delPref ()
	{
    	// au nevoie de contextul aplicatiei deci nu le pot pune in clasa pentru delogare
    	SharedPreferences logPref = getSharedPreferences("LoginPref", MODE_PRIVATE);
    	SharedPreferences.Editor prefEditor = logPref.edit();
    	prefEditor.clear();
    	prefEditor.commit();
	}
	
	private void gotoLogin()
	{
		Intent intent = new Intent(getApplicationContext(), Login.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
	
		finish();
	}
	/**** end delogare ****/
	
	
}